package com.samphanie.dries.component;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.samphanie.dries.properties.AppProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2021/3/4 13:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AliComponent {

    private final AppProperties appProperties;

    public void sendSms(String mobile, String template, Map<String, Object> params) {

        String signName = appProperties.getAli().getAliSms().getSignName();
        String accessKeyId = appProperties.getAli().getAliSms().getAccessKeyId();
        String accessKeySecret = appProperties.getAli().getAliSms().getAccessKeySecret();
        String templateCode = appProperties.getAli().getAliSms().getTemplate().get(template);

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("TemplateCode", templateCode);
        if (CollUtil.isNotEmpty(params)) {
            request.putQueryParameter("TemplateParam", JSONUtil.toJsonStr(params));
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.debug("短信发送结果: {}", response.getData());
        } catch (ServerException e) {
            log.error("发送短信时产生服务端异常 {}", e.getLocalizedMessage());
        } catch (ClientException e) {
            log.error("发送短信时产生客户端异常 {}", e.getLocalizedMessage());
        }
    }


}
